// pages/addWarehouse/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableList: [],
    tableItem: {
      // 储存库库区相关
      warehouseId: '',
      warehouseName: '',
      areaId: '',
      areaName: '',

      // 存储产品相关
      productName: '',
      productTypeName: '',
      productId: '',
      productTypeId: '', 

      attachment: '', // 照片
      realWeight: '', // 重量
      orderWeight: '', // 估计重量
    },
    handType:"",//操作类型

    /**
       * 选择储藏产品
    */
    productFlag: false, // 弹窗开关
    productList: [],

    fieldNames: {
      text: 'label',
      value: 'id'
    },

    /**
       * 选择储存库、库区
    */
    wareFlag: false, // 弹层开关
    wareList: [],

    wareNames: {
      text: 'warehouseName',
      value: 'id'
    },

    index: 0, // 当前操作对象
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let type=options.type

    if(type=="in"){//入库库
      wx.setNavigationBarTitle({
        title: '新增入库',
      })
    }else{//出库
      wx.setNavigationBarTitle({
        title: '新增出库',
      })
    }

    // 进入时，默认给列表塞一个空对象
    this.setData({
      handType:type,
      tableList: [{
        // 储存库库区相关
        warehouseId: '',
        warehouseName: '',
        areaId: '',
        areaName: '',

        // 存储产品相关
        productName: '',
        productTypeName: '',
        productId: '',
        productTypeId: '', 

        attachment: '', // 照片
        realWeight: '', // 重量
        orderWeight: '', // 估计重量
      }]
    })

    // 请求存储产品的数据
    wx.$req({
      url: '/wms/itemType/treeselect',
    }).then(res => {
      this.setData({ 
        productList: res.data.data,
      })
    })

    // 请求储存库/库区数据
    wx.$req({
      url: '/wms/warehouse/tree',
    }).then(res => {

      // 不要根节点
      // 并且， 没有库区的仓库要设置禁选
      const result = res.data[0].children
      result.forEach(item => {
        if (item.children.length === 0) {
          item.disabled = true
        }
      })
      this.setData({  wareList: result })
    })
  },

  // 新增
  addHandle() {
    const tableList = this.data.tableList
    tableList.push({...this.data.tableItem})

    this.setData({ tableList })
  },

  /* 存储产品级联选择相关 */
  // 关闭弹窗，同时清空内容
	onClose (e) {
		this.setData({ productFlag: false,  })
	},

	// 打开级联选择弹窗
	openProduct (e) {
    const index = e.currentTarget.dataset.index
    
		this.setData({  productFlag: true, index })
	},

	// 级联选择完毕 存储产品
	onFinish (e) {
		const result = e.detail.selectedOptions

		let productName = result[1].label,
		productTypeName = result[0].label,
		productId = result[1].id,
		productTypeId = result[0].id

		const tableList = this.data.tableList
		Object.assign(tableList[this.data.index], { productName, productTypeName, productId, productTypeId })

    // 同时新增一个数组
    tableList[this.data.index].categorization = [productTypeId, productId]
    
    this.setData({
      tableList
    }, () => this.onClose())
	},

  // 关闭弹窗，同时清空内容
	onCloseWare () {
		this.setData({ wareFlag: false })
	},

  /* 储存库、库区 级联选择相关 */
	// 打开级联选择弹窗
	openWare (e) {
    const index = e.currentTarget.dataset.index

		this.setData({  wareFlag: true, index })
	},

	// 级联选择完毕
	onFinishWare (e) {
    const result = e.detail.selectedOptions


		let warehouseName = result[0].warehouseName,
		areaName = result[1].warehouseName,
		warehouseId = result[0].id,
    areaId = result[1].id

    const tableList = this.data.tableList

		Object.assign(tableList[this.data.index], { warehouseName, areaName, warehouseId, areaId })

    // 同时新增一个数组
    tableList[this.data.index].place = [areaId, warehouseId]
    
    this.setData({
      tableList
    }, () => this.onCloseWare())


  },
  
 

  // 输入框回调
	onChange(e) {

		const field = e.target.dataset.field
    const index = e.target.dataset.index

    if (field === 'realWeight') {

      if (e.detail > 999999) {
        return wx.showToast({
          title: `请输入合理的重量`,
          icon: 'none'
        })
        return
      }
    }
    
		const tableList = this.data.tableList
    tableList[index][field] = e.detail

  },
  
  // 图片上传回调
  imgHandle (e) {
    const { index, list } = e.detail

    const tableList = this.data.tableList
    
    tableList[index].attachment = JSON.stringify(list)
    this.setData({
      tableList
    })
  },

  // 删除某一项
  del (e) {
    const index = e.currentTarget.dataset.index

    const tableList = this.data.tableList
    tableList.splice(index, 1)

    this.setData({ tableList })
  },

  // 提交
  submit() {

    // 需要校验的字段
    const requireField = [
      { field: 'areaId', text: '请选择储存库/库区' },
      { field: 'productTypeId', text: '请选择存储产品' },
      { field: 'realWeight', text: '请填写重量' },
    ]

    // 校验
    const tableList = this.data.tableList

    for (let i = 0; i < tableList.length; i++) {

      const obj = tableList[i]

      for (let key in obj) {

        // 查找key 是否在必填项中
        const resIndex = requireField.findIndex(item => item.field === key)

        // 未填项提示
        if (!obj[key] && (resIndex > -1)) {
          return wx.showToast({
            title: `第${i + 1}项${requireField[resIndex].text}`,
            icon: 'none'
          })
        }

        console.log(key)

        // 重量验证
        if (key === 'realWeight') {

          if (obj[key] == 0 || obj[key] > 999999) {
            return wx.showToast({
              title: `第${i + 1}项请输入合理的重量`,
              icon: 'none'
            })
          }
        }
      }

    }

    let url=""
    if(this.data.handType=="in"){//入库
        url="/wms/transactions/into/add"
    }else{//出库
      url="/wms/transactions/out/add"
    }

    // 校验通过
    wx.$req({
      url: url,
      method: 'post',
      data: JSON.stringify(this.data.tableList),
      loadingText: '提交中..'
    }).then(res => {
      
      wx.hideLoading()
      if(res.data.code==500){
        wx.showToast({
          title: '新增异常，请联系管理员',
          icon: 'none'
        })
      }else{
          wx.showToast({
            title: '新增成功',
            icon: 'success'
          })

          wx.navigateBack()
      }
    }).catch(res =>{
      wx.hideLoading()
      if(res.data.code==500){
       
        if(res.data.msg==''){
          wx.showToast({
            title: '新增异常',
            icon: 'error'
          })
        }else{
          wx.showToast({
            title: res.data.msg.replace('{','').replace('}',''),
            icon: 'none'
          })
        }
      }
    })

  }

})